<?php

namespace app\api\service;
use app\Response;
use app\api\model\User;
use think\facade\Cache;
class LoginService
{

    public static function loginService($data){
        $where[] = ["username|phone","=",$data["account"]];
        $find = User::userInfo($where);
        if(!empty($find)){
            $find = $find->toArray();
            $encryption = $find['encryption'];
        }else{
            return Response::wrapError(0,'用户名密码错误');
        }
        if($find['type'] != 15){
            return Response::wrapError(0,"当前账号非快递手机端！");
        }
        if($find['enable'] == 0){
            return Response::wrapError(0,'账号被锁定');
        }
        if($find['password'] !== self::encPassword($data['password'],$encryption)){
            return Response::wrapError(0,'账号或密码错误');
        }
        $get_real_ip = self::get_real_ip();
        User::userEdit(['uid'=>$find['uid']],['lasttime'=>time(),'last_ip'=>$get_real_ip]);
        session('uid', $find['uid']);
        session('username', $data["account"]);
        session('type', $find['type']);

        $info = [];
        $info['uid'] = $find['uid'];
        $info['username'] =  $data["account"];
        $info['type'] =  $find['type'];
        $newStr = self::str_random(8);
        if (Cache::has("user-token".$info["uid"])){
            Cache::set("user-token".$info["uid"],"");
            Cache::set("user-token".$info["uid"],$newStr,43200);
        }else{
            Cache::set("user-token".$info["uid"],$newStr,43200);
        }
        $info['auth_token'] = $newStr;
        return Response::wrapData($info);
    }


    public static function useInfoService($uid){
        $User = User::userInfo(["uid"=>$uid]);
        if(empty($User)){
            return Response::wrapError(-200,'非法请求');
        }
        if($User['type'] != 15){
            return Response::wrapError(-200,'账户非快递手机端!');
        }
        if($User['enable'] == 0){
            return Response::wrapError('此账户已被禁用,如有疑问请联系客服人员',-200);
        }
        $info = $User;
        $info["pa_name"] = User::userInfo(["uid"=>$User["paid"]])["nickname"];
        return Response::wrapData($User);
    }

    public static function useEdisPassword($uid,$password){
        $User = User::userInfo(["uid"=>$uid]);
        if(empty($User)){
            return Response::wrapError(-200,'非法请求');
        }
        if($User['type'] != 15){
            return Response::wrapError(-200,'账户非快递手机端!');
        }
        if($User['enable'] == 0){
            return Response::wrapError('此账户已被禁用,如有疑问请联系客服人员',-200);
        }
        $encryption = self::createNonceStr($length = 4);
        $password = self::encPassword($password,$encryption);//密码
        $data["password"] = $password;
        $data["encryption"] = $encryption;
        $res = User::userEdit(["uid"=>$uid],$data);
        if($res){
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"修改失败!");
        }
    }

    //获取客户端IP
    public static function get_real_ip()
    {
        $ip=FALSE;
        //客户端IP 或 NONE
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
            for ($i = 0; $i < count($ips); $i++) {
                if (!preg_match("(10│172.16│192.168)", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        //客户端IP 或 (最后一个)代理服务器 IP
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

    //密码加密
    public static function encPassword($password,$encryption){
        $enc = md5(md5($password).$encryption);
        return $enc;
    }

    /**
     * 生成随机字符串
     * @param int $user_id
     * @param array $data
     * @return string
     */
    public static function str_random($length = 16)
    {
        $string = '';
        while (($len = strlen($string)) < $length) {
            $size = $length - $len;
            $bytes = random_bytes($size);
            $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
        }
        return $string;
    }


    /**
     * 生成随机字符串
     * @param int $length
     * @return string
     */
    public static function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}